<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="发文时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admDocumentSend:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:admDocumentSend:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admDocumentSend:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admDocumentSend:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admDocumentSendList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="拟稿人id" align="center" prop="draftId" >
          <template #default="scope">
            <span>{{ scope.row.draftName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="projectId" >
          <template #default="scope">
            <el-tooltip :content="scope.row.projectName" placement="top" :disabled="!scope.row.projectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.projectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="发文时间" align="center" prop="dispatchTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.dispatchTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发文标题" align="center" prop="dispatchTitle" >
          <template #default="scope">
            <el-tooltip :content="scope.row.dispatchTitle" placement="top" :disabled="!scope.row.dispatchTitle">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.dispatchTitle }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="发文字号" align="center" prop="dispatchNumber" >
          <template #default="scope">
            <el-tooltip :content="scope.row.dispatchNumber" placement="top" :disabled="!scope.row.dispatchNumber">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.dispatchNumber }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="发文类型" align="center" prop="dispatchType" >
          <template #default="scope">
            <dict-tag :options="send_document_type" :value="scope.row.dispatchType" />
          </template>
        </el-table-column>
        <el-table-column label="主送公司" align="center" prop="mainCompany" >
          <template #default="scope">
            <el-tooltip :content="scope.row.mainCompany" placement="top" :disabled="!scope.row.mainCompany">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.mainCompany }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="抄送公司" align="center" prop="ccCompany" >
          <template #default="scope">
            <el-tooltip :content="scope.row.ccCompany" placement="top" :disabled="!scope.row.ccCompany">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.ccCompany }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="份数" align="center" prop="copies" />
        <el-table-column label="审批状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:admDocumentSend:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:admDocumentSend:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改发文审批对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
      class="seal-dialog"
    >
      <template #default>
        <el-form ref="admDocumentSendFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="拟稿人" prop="draftId">
                <el-input v-model="form.draftName" placeholder="请输入拟稿人名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="部门" prop="deptId">
                <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目名称" prop="projectName">
                <el-tree-select
                  v-model="form.projectName"
                  :data="projectTree"
                  placeholder="请选择项目名称"
                  :props="{ label: 'contractName', value: 'id', children: 'children' }"
                  filterable
                  clearable
                  style="width: 100%"
                  @change="handleProjectChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发文时间" prop="dispatchTime">
                <el-date-picker clearable
                  v-model="form.dispatchTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择发文时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发文标题" prop="dispatchTitle">
                <el-input v-model="form.dispatchTitle" placeholder="请输入发文标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发文字号" prop="dispatchNumber">
                <el-input v-model="form.dispatchNumber" placeholder="请输入发文字号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发文类型" prop="dispatchType">
                <el-select
                  v-model="form.dispatchType"
                  placeholder="请选择发文类型"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="option in send_document_type"
                    :key="option.value"
                    :label="option.label"
                    :value="Number(option.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="主送单位" prop="mainCompany">
                <el-input v-model="form.mainCompany" placeholder="请输入主送单位" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="抄送单位" prop="ccCompany">
                  <el-tree-select
                      v-model="form.ccCompany"
                      :data="deptTree"
                      placeholder="请选择部门"
                      :props="{ label: 'label', value: 'id', children: 'children' }"
                      check-strictly
                      filterable
                      :default-expand-all="true"
                      style="width: 100%"
                      @visible-change="handleVisibleChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="份数" prop="copies">
                <el-input v-model="form.copies" placeholder="请输入份数" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件上传" prop="attachmentId">
                <el-input v-model="form.attachmentName" placeholder="请点击附件上传" @click="handleAttachmentUpload(6)"/>
              </el-form-item>
            </el-col>
          </el-row>    
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        v-model:file-list="uploadRefFileList"
        accept=".pdf"
        :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-remove="handleFileRemove"
        :auto-upload="false"
        :multiple="true"
        drag
        list-type="picture"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入.pdf 文件图片格式。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate"
              >下载模板</el-link
            > -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="AdmDocumentSend" lang="ts">
import { listAdmDocumentSend, getAdmDocumentSend, delAdmDocumentSend, addAdmDocumentSend, updateAdmDocumentSend } from '@/api/general/administration/document/send';
import { AdmDocumentSendVO, AdmDocumentSendQuery, AdmDocumentSendForm } from '@/api/general/administration/document/send/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { listProContract } from '@/api/project/init/contract';
import { pageListProInfo } from '@/api/project/init/proInfo';
import { ItemTreeNode } from '@/api/project/init/contract/types';
import { globalHeaders } from '@/utils/request';
import { UploadQuery } from '@/api/general/administration/car/upload/types';
import { uploadAttachment, deleteUploadFile, queryAllByUser } from '@/api/general/administration/car/apply';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 全局配置
const BASE_URL = import.meta.env.VITE_APP_BASE_API || 'http://localhost:8080';
const admDocumentSendList = ref<AdmDocumentSendVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 引入数据字典
const { send_document_type, approval_record_status } = toRefs<any>(proxy?.useDict('send_document_type', 'approval_record_status'));

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);
// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["综合整治院", "规划院", "工程中心"];

// 导入相关
const uploadRef = ref<any>();
// 已上传文件，用于回显和 form.attachment
const uploadedFiles = ref<any[]>([]);
// 当前待上传文件列表
const uploadRefFileList = ref<any[]>([]);
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 上传的类型
  type: undefined,
  // 设置上传的请求头部
  headers: globalHeaders()
});

const queryFormRef = ref<ElFormInstance>();
const admDocumentSendFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

/**
 * 生成32位UUID
 * @returns string 32位UUID
 */
function generateUUID32(): string {
  // 生成标准 UUID v4，然后去掉 "-"
  return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, () =>
    ((Math.random() * 16) | 0).toString(16)
  );
}


/**
 * 初始化或获取表单关联的 number
 * @param form - 表单对象
 * @param isNew - 是否是新增表单
 */
const initOrAssignNumber = (form: AdmDocumentSendForm, isNew: boolean) => {
  if (isNew) {
    // 新增场景：如果 number 为空，生成新的 UUID
    if (!form.number) {
      form.number = generateUUID32()
    }
  } else {
    // 修改场景：保证 number 已存在，否则抛错提示
    if (!form.number) {
      throw new Error('修改表单时 number 不存在，无法保持关联！')
    }
    // 不做生成，直接使用已有 number
  }
  return form.number
}

const initFormData: AdmDocumentSendForm = {
  id: undefined,
  draftId: userStore.userId,
  draftName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  projectId: undefined,
  projectName: undefined,
  dispatchTime: formatLocalDate(),
  dispatchTitle: undefined,
  dispatchNumber: undefined,
  dispatchType: undefined,
  mainCompany: undefined,
  ccCompany: undefined,
  copies: undefined,
  attachmentId: undefined,
  attachmentName: undefined,
  number: undefined,
  status: undefined,
  approverIdea: undefined,
}
const data = reactive<PageData<AdmDocumentSendForm, AdmDocumentSendQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    draftId: undefined,
    deptId: undefined,
    projectId: undefined,
    dispatchTime: undefined,
    dispatchTitle: undefined,
    dispatchNumber: undefined,
    dispatchType: undefined,
    mainCompany: undefined,
    ccCompany: undefined,
    copies: undefined,
    attachmentId: undefined,
    number: undefined,
    status: undefined,
    approverIdea: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
     deptId: [
      { required: true, message: "部门id不能为空", trigger: "blur" }
    ],
    projectName: [
      {
        validator: (rule, value, callback) => {
          // 当部门是指定部门时，项目名称必填
          const selectedDept = findDeptNode(deptTree.value, form.value.deptId);
          console.log(selectedDept);
          if (selectedDept && requiredProjectDepts.includes(selectedDept.label)) {
            if (!value) {
              return callback(new Error(selectedDept.label + "归还资产项目名称必填"));
            }
          }
          callback();
        },
        trigger: "change"
      }
    ],
    draftId: [
      { required: true, message: '拟稿人不能为空', trigger: 'blur' }
    ],
    dispatchTime: [
      { required: true, message: '请选择发文时间', trigger: 'change' }
    ],
    dispatchTitle: [
      { required: true, message: '请输入发文标题', trigger: 'blur' }
    ],
    dispatchNumber: [
      { required: true, message: '请输入发文字号', trigger: 'blur' }
    ],
    dispatchType: [
      { required: true, message: '请选择发文类型', trigger: 'change' }
    ],
    mainCompany: [
      { required: true, message: '请输入主送单位', trigger: 'blur' }
    ],
    ccCompany: [
      { required: true, message: '请输入抄送单位', trigger: 'blur' }
    ],
    copies: [
      { required: true, message: '请输入份数', trigger: 'blur' },
      { pattern: /^[1-9]\d*$/, message: '份数必须为正整数', trigger: 'blur' }
    ],
    attachmentId: [
      { required: false, message: '请上传附件', trigger: 'change' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询发文审批列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmDocumentSend(queryParams.value);
    admDocumentSendList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  admDocumentSendFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmDocumentSendVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加发文审批";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmDocumentSendVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getAdmDocumentSend(_id);
  Object.assign(form.value, {
    ...res.data,
    dispatchType: Number(res.data.dispatchType)
  });
  // 初始化附件列表，但不要打开弹窗
  if (form.value.number && form.value.draftId) {
    await loadAttachments(); // 仅刷新上传组件列表，不操作 upload.open
  }
  console.log("1111111111",form.value.dispatchType)
  console.log("2222222222",send_document_type)
  dialog.visible = true;
  dialog.title = "修改发文审批";
}

/** 提交按钮 */
const submitForm = () => {
  admDocumentSendFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmDocumentSend(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAdmDocumentSend(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmDocumentSendVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除发文审批编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmDocumentSend(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admDocumentSend/export', {
    ...queryParams.value
  }, `admDocumentSend_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取全部子项目（树级赋值，父节点不可选择）
const fetchProjectList = async () => {
  try {
    // 1. 获取合同列表
    const contractRes = await listProContract();
    const contracts = (contractRes?.rows || []).filter(
      (c: any) => c.contractStatus == 3
    );
    // 2. 获取项目列表
    const projectRes = await pageListProInfo();
    const projects = projectRes?.rows || [];
    // 3. 构建树结构
    const treeData = contracts.map((contract: any) => {
      const children = projects
        .filter((p: any) => p.contractId === contract.id)
        .map((p: any) => ({
          id: p.id,
          contractName: `${p.proName} (${p.proNumber})`, // 拼接 proName 和 proNumber
          contractId: contract.id
        }));

      return {
        id: contract.id,
        contractName: contract.contractName, // 父节点显示合同名
        disabled: true,
        children
      };
    });

    projectTree.value = treeData;
  } catch (error) {
    console.error("获取项目列表失败:", error);
    proxy?.$modal.msgError("获取项目列表失败");
  }
};

const handleProjectChange = (selectedId: number) => {
  // 根据 selectedId 找到对应项目对象
  const findProject = (nodes: any[]): any => {
    for (const node of nodes) {
      if (node.id === selectedId) return node;
      if (node.children) {
        const child = findProject(node.children);
        if (child) return child;
      }
    }
    return null;
  };

  const project = findProject(projectTree.value);
  if (project) {
    form.value.projectId = project.id;
    form.value.projectName = project.contractName; // 或者 proName/proNumber 组合
  } else {
    form.value.projectId = null;
    form.value.projectName = '';
  }
};

// 递归查找部门节点
function findDeptNode(tree: any[], deptId: string | number): any {
  for (const node of tree) {
    if (node.id === deptId) return node;
    if (node.children && node.children.length > 0) {
      const found = findDeptNode(node.children, deptId);
      if (found) return found;
    }
  }
  return null;
}

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};


/**
 * 提交上传文件
 */
const submitFileForm = async () => {
  const files = uploadRefFileList.value.map(f => f.raw).filter(Boolean);
  if (!files.length) {
    ElMessage.warning("请先选择文件！");
    return;
  }

  upload.isUploading = true;
  try {
    await uploadAttachment(files, data.form.draftId, data.form.number, upload.type);

    // 上传成功后刷新附件列表
    await loadAttachments();

    // ⚠️ 触发回调，更新表单或者其他需要刷新逻辑
    // 例如：重新计算 attachmentId / attachmentName 已在 loadAttachments 里处理

    ElMessage.success("上传成功");

    // 清空临时待上传文件
    uploadRefFileList.value = [];
    uploadRef.value?.clearFiles();

    // 强制关闭上传弹窗，防止自动弹出
    upload.open = false;

  } catch (err) {
    console.error(err);
    ElMessage.error("上传失败，请重试");
  } finally {
    upload.isUploading = false;
  }
};



/**
 * 打开附件上传弹窗
 */
const handleAttachmentUpload = (type: number) => {
  upload.title = '附件信息上传';
  upload.type = type;
  upload.open = true; // 只有用户点击才打开
    // 加载附件列表数据，但不要重复打开弹窗
  loadAttachments(); // 只是刷新列表，不操作 upload.open
};

 // 页面初始化或表单加载完成后调用
const loadAttachments = async () => {
  if (!data.form.number || !data.form.draftId) return; // 新增表单未生成number或useId，不加载

  try {
    const query: UploadQuery = {
      number: data.form.number,
      uploadId: data.form.draftId
    };

    const response = await queryAllByUser(query);
    const existingFiles = response.data || [];

    uploadedFiles.value = existingFiles.map(f => ({
      id: f.id,
      name: f.name,
      url: f.url || '',
      fullUrl: getFileUrl(f.url),
      raw: null
    }));

    uploadRefFileList.value = uploadedFiles.value.map(f => ({
      name: f.name,
      url: f.fullUrl,
      status: 'success',
      raw: f.raw,
      id: f.id
    }));

    // 更新表单 attachment 字段
    form.value.attachmentId = uploadedFiles.value.map(f => f.id).join(',');
    form.value.attachmentName = uploadedFiles.value.map(f => f.name).join(',');

  } catch (err) {
    console.error('附件加载失败', err);
    ElMessage.error('附件加载失败');
  }
};


// 取消上传
const cancelUpload = () => {
  upload.open = false;
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
};

// 获取完整 URL
const getFileUrl = (url: string) => {
  if (!url) return '';
  // 已经是完整路径就直接返回
  if (url.startsWith('http') || url.startsWith('file://')) return url;
  // 去掉前面的 '/upload'，然后拼接
  const fileName = url.substring(url.lastIndexOf('/') + 1); 
  return `${BASE_URL}upload/${fileName}`;
};

/**
 * 删除单个文件
 * @param file 当前删除的文件对象
 * @param index 文件在 file-list 中的索引
 */
const handleFileRemove = async (file: any, fileList: any[]) => {
  console.log("准备删除的文件:", file, fileList);
  try {
    if (file.id) {
      await deleteUploadFile(file.id);
    }
    ElMessage.success(`${file.name} 已删除`);
    // 删除后刷新附件列表
    await loadAttachments();
  } catch (err) {
    console.error('删除文件失败', err);
    ElMessage.error(`删除文件 ${file.name} 失败`);
  }
};

onMounted(() => {
  getList();
  fetchDeptTree();
  fetchProjectList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>